﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using NigiriClub.WebUI.Utils.PagingHelper;


namespace NigiriClub.WebUI.Models.PagedCollections
{
    public class NewswireViewModel
    {
        public List<News> News { get; set; }
        public PagingInfo PageInfo { get; set; }

        public NewswireViewModel(int currentPage)
        {
            using (Entities db = new Entities())
            {
                PageInfo = new PagingInfo()
                {
                    TotalItems = db.News.Count(u => true),
                    ItemsPerPage = 10,
                    CurrentPage = currentPage
                };

                News = db.News.OrderByDescending(p => p.Date)
                          .Skip((PageInfo.CurrentPage - 1) * PageInfo.ItemsPerPage)
                          .Take(PageInfo.ItemsPerPage).ToList();
            }
        }

        private int getCategoryId(Entities db, string categoryName)
        {
            Category category = db.Category.FirstOrDefault(c => c.Name == categoryName);
            return category == null ? -1 : category.Id;
        }

        private int getTagId(Entities db, string tagName)
        {
            Tag tag = db.Tag.FirstOrDefault(c => c.Name == tagName);
            return tag == null ? -1 : tag.Id;
        }

        private IEnumerable<News> getSelected(Entities db, string tagName, string categoryName)
        {
            IEnumerable<News> news;

            int categoryId = getCategoryId(db, categoryName);
            int tagId = getTagId(db, tagName);

            if (tagId == -1)
            {
                news = db.News;
            }
            else
            {
                news = db.Tag.FirstOrDefault(t => t.Id == tagId).News;
            }

            return news.Where(n => categoryId == -1 || n.CategoryId == categoryId);
        }

        public NewswireViewModel(int currentPage, string tagName, string categoryName)
        {
            using (Entities db = new Entities())
            {
                PageInfo = new PagingInfo()
                {
                    TotalItems = db.News.Count(u => true),
                    ItemsPerPage = 10,
                    CurrentPage = currentPage
                };

                News = getSelected(db, tagName, categoryName)
                    .OrderByDescending(p => p.Date)
                    .Skip((PageInfo.CurrentPage - 1) * PageInfo.ItemsPerPage)
                    .Take(PageInfo.ItemsPerPage).ToList();
                foreach (var n in News)
                {
                    n.TagList = n.Tag.ToList();
                }
            }
        }
    }
}